<?php

namespace app\command;

use catchAdmin\product\model\Pack;
use catchAdmin\product\model\Product;
use catchAdmin\storehouse\model\Project;
use catchAdmin\storehouse\model\Warehousing;
use catchAdmin\storehouse\model\WarehousingSon;
use Exception;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
use think\facade\Log;

class SyncGoods extends Command
{
    protected function configure()
    {
        $this->setName('SyncGoods')
            ->setDescription('同步商品');
    }

    protected function execute(Input $input, Output $output)
    {
        //return $output->write('tttt==='.date('ymdHis'));
        $orData = Db::connect('oracle')->table('tm_part')
            ->field(
                '
                NAME as "goods_name",
                TM_PART_ID as "goods_id",
                MACHINE_TYPE as "company",
                NO as "serial_number",
                MACHINE_REMARK as "describe",
                QR_CODE as "barcode",
                MACHINE_TYPE as "sku"
                ')->where([
                'DELETE_STATUS' => '0',
            ])->where(function ($query) {
                $query->whereOr('NO', 'like', '1A04-%');
                $query->whereOr('NO', 'like', '1A01-%');
            })->select()->toArray();
        //return $output->write(json_encode($orData));
//->where('TM_PART_ID', '4d306c6620d5498da0763944c360e160')
        Db::startTrans();
        try {
            if (!empty($orData)) {
                $proInfo = Project::where([
                    'pid' => 0,
                    'tenant_id' => 10175,
                    'deleted_at' => 0,
                ])->find();
                $packInfo = Pack::where('tenant_id', 10175)->find();
                foreach ($orData as $oKey=>$oVal) {
                    $lnum=$oKey+1;
                    $output->writeln($lnum."=1===".$oVal['goods_id'].'====');
                    $pinfo = Product::where([
                        'goods_id'=> $oVal['goods_id'],
                        'deleted_at' => 0,
                    ])->find();
                    $output->writeln($lnum."=2===".$oVal['goods_id'].'====');
                    $arr = [
                        "goods_name" => $oVal["goods_name"],
                        "goods_Cname" => $oVal["goods_name"],
                        "goods_Ename" => $oVal["goods_name"],
                        "company" => $oVal["company"],
                        "serial_number" => $oVal["serial_number"],
                        "describe" => $oVal["describe"],
                        "packing_id" => $packInfo['packing_id'] ?? '',
                        "barcode" => date('mdHis') . rand(1000, 9999),
                        "goods_id" => $oVal['goods_id'],
                        "tenant_id" => 10175,
                        "creator_id" => 10175,
                        'created_at' => time(),
                        "sku" => $oVal["sku"],
                    ];

                    $output->writeln($lnum."=3===".$oVal['goods_id'].'====');
                    if (empty($pinfo)) {
                        $goodsId = Product::insert($arr,true);
                        $output->writeln($lnum."=33===".$oVal['goods_id'].'====goodsId'.$goodsId);
                        $projectId = Project::where([
                            'tenant_id' => 10175,
                            'deleted_at' => 0,
                            'pid' => $proInfo['id']
                        ])->value('project_id');
                        $output->writeln($lnum."=4===".$oVal['goods_id'].'====goodsId'.$goodsId);
                        $num = 100000000;
                        if (!empty($goodsId)) {
                            $base = base_convert(uniqid(), 36, 10);
                            $idNo = date('ymdHis').substr($base, -6);
                            $inData = [
                                "tenant_id" => 10175,
                                "warehousing_id" => $idNo,
                                "project_id" => $proInfo['project_id'] ?? '',
                                "project_client" => $projectId ?? '',
                                "new_order_date" => date('Y-m-d', time()),
                                'warehousing_config_attribute' => '1,0',
                                'goods_number' => $num,
                                'actual_number' => $num,
                                'status' => 1,
                                "creator_id" => 10175,
                                'created_at' => time()
                            ];
                            $output->writeln($lnum."=5===".$oVal['goods_id'].'====goodsId='.json_encode($inData));
                            Warehousing::insert($inData);
                            $output->writeln($lnum."==6==".$oVal['goods_id']);
                            $base = base_convert(uniqid(), 36, 10);
                            $idNo = date('ymdHis').substr($base, -6);
                            $orderGoods = [
                                "batch_number" => 'p' . date('mdHis') . rand(1000, 9999),
                                "creator_id" => 10175,
                                "enter_type" => 1,
                                "goods_id" => $oVal['goods_id'],
                                "goods_name" => $oVal["goods_name"],
                                "number" => $num,
                                "packing_id" => $packInfo['packing_id'],
                                "tenant_id" => 10175,
                                "type" => "add",
                                'actual_number' => $num,
                                'status' => 1,
                                'created_at' => time(),
                                "warehousing_id" => $inData['warehousing_id'],
                                "warehousing_son_config_attribute" => "1,9545",
                                "warehousing_son_id" => $idNo
                            ];

                            $params = $this->goods_info($orderGoods);
                            $trayBoxNum = (new Pack)->getTrayBoxNum($params['data']['number'], $params['data']['packing_id']);
                            $params['data']['tray_number'] = $trayBoxNum['tray_num'];
                            $params['data']['box_number'] = $trayBoxNum['box_num'];
                            $params['data']['specification'] = $packInfo['packing_num'] . ' / ' . $packInfo['unit_name'] . " /" . $packInfo['layup_num'];
                            $sonId = WarehousingSon::insert($params['data'], true);
                            $output->writeln("===".$oVal['goods_id'].'====sonId'.$sonId);
                            $trayId = $this->inGoods($params['data'], $packInfo);
                            $output->writeln("===".$oVal['goods_id'].'====trayId'.$trayId);
                            $stockId = $this->in($trayId, $params['data'], $inData, $packInfo);
                            $output->writeln("===".$oVal['goods_id'].'====stockId'.$stockId);
                            $logId = $this->inLog($stockId, $params['data'], $packInfo);
                            $output->writeln("===".$oVal['goods_id'].'====logId'.$logId);

                        }
                    }
                }
            }
            Db::commit();
            return $output->writeln('同步MES商品数据，插入数据成功！');
        } catch (\Exception $exception) {
            Db::rollback();
            return $output->writeln('同步MES商品数据，插入数据失败！'.$exception->getMessage());
        }
    }

    /**
     * 商品信息
     * @return array
     */
    public function goods_info($params)
    {
        //入库数量对比
        $where1['warehousing_id'] = $params['warehousing_id'];
        $where1['deleted_at'] = 0;
        $goods_number = DB::name('db_warehousing')->where($where1)->value('goods_number');
        if ($params['type'] === 'edit') {
            $where[] = ['id', '<>', $params['id']];
        }

        $where[] = ['warehousing_id', '=', $params['warehousing_id']];
        $where[] = ['deleted_at', '=', 0];

        $number = Db::name('db_warehousing_son')->field('SUM(number) as number')->where($where)->find();

        $number1 = intval($number['number']) + intval($params['number']);

        if ($number1 > $goods_number) {
            return array('code' => 0, 'msg' => '商品数量大于商品总数量，请核对商品数量');
        }

        //商品
        $where2['goods_id'] = $params['goods_id'];
        $where2['deleted_at'] = 0;
        $info = DB::name('db_product')
            ->field('barcode,goods_name,goods_Ename,goods_Cname,supplier_id,manufacturer_id,HSCODE')
            ->where($where2)
            ->find();

        $params['HSCODE'] = $info['HSCODE'];
        $params['goods_name'] = $info['goods_name'];
        $params['goods_Ename'] = $info['goods_Ename'];
        $params['goods_Cname'] = $info['goods_Cname'];
        $params['supplier_id'] = $info['supplier_id'];
        $params['manufacturer_id'] = $info['manufacturer_id'];
        $where3['supplier_id'] = $info['supplier_id'];
        $where3['deleted_at'] = 0;
        $params['supplier_name'] = DB::name('db_supplier')->where($where3)->value('supplier_name');
        $where4['manufacturer_id'] = $info['manufacturer_id'];
        $where4['deleted_at'] = 0;
        $params['manufacturer_name'] = DB::name('db_manufacturer')->where($where4)->value('manufacturer_name');
        //包装
        $where5['packing_id'] = $params['packing_id'];
        $where5['deleted_at'] = 0;
        $packing = DB::name('db_packing')
            ->field('packing_id,packing_num,unit_name')
            ->where($where5)
            ->find();

        $params['p_barcode'] = $packing['packing_id'];
        $params['packing_num'] = $packing['packing_num'];
        $params['unit_name'] = $packing['unit_name'];

        unset($params['type']);
        return array('code' => 1, 'msg' => '', 'data' => $params);
    }

    public function inGoods($goodsInfo, $packInfo)
    {
        $base = base_convert(uniqid(), 36, 10);
        $idNo = date('ymdHis').substr($base, -6);
        $data = [];
        $data['tray_id'] = 'JXRDT' . $idNo;
        $data['warehousing_id'] = $goodsInfo['warehousing_id'];
        $data['warehousing_son_id'] = $goodsInfo['warehousing_son_id'];
        $data['config_id'] = "20250708142453";
        $data['tenant_id'] = 10175;
        $data['status'] = '0';
        $data['goods_status'] = 'Good';
        $data['created_at'] = time();
        $data['box_number'] = $goodsInfo['box_number'];
        $data['number'] = $goodsInfo['number'];
        $data['batch_number'] = $goodsInfo['batch_number'];
        $data['creator_id'] = 10175;
        $data['status'] = 1;
        $data['updated_at'] = time();
        //goods
        $product['warehousing_id'] = $goodsInfo['warehousing_id'];
        $product['warehousing_son_id'] = $goodsInfo['warehousing_son_id'];
        $product['goods_name'] = $goodsInfo['goods_name'];
        $product['goods_id'] = $goodsInfo['goods_id'];
        $product['goods_Cname'] = $goodsInfo['goods_Cname'];
        $product['goods_Ename'] = $goodsInfo['goods_Ename'];
        $product['manufacturer_id'] = $goodsInfo['manufacturer_id'];
        $product['manufacturer_name'] = Db::table('db_manufacturer')->where('manufacturer_id', $goodsInfo['manufacturer_id'])->value('manufacturer_name');
        $product['supplier_id'] = $goodsInfo['supplier_id'];
        $product['supplier_name'] = Db::table('db_supplier')->where('supplier_id', $goodsInfo['supplier_id'])->value('supplier_name');
        $product['packing_id'] = $packInfo['packing_id'];
        $product['p_barcode'] = $packInfo['packing_id'];
        $product['packing_num'] = $packInfo['packing_num'];
        $product['unit_name'] = $packInfo['unit_name'];
        $product['number'] = $goodsInfo['number'];
        $product['box_number'] = $goodsInfo['box_number'];
        $product['created_at'] = time();
        $product['tenant_id'] = 10175;
        $product['creator_id'] = 10175;
        $product['tray_id'] = $data['tray_id'];
        $product['status'] = 1;
        $product['specification'] = $packInfo['packing_num'] . ' / ' . $packInfo['unit_name'] . ' /' . $packInfo['layup_num'];
        //【硬】删除之前系统默认分配的托盘表和入库托盘产品表
        Db::table('db_tray')->where('warehousing_son_id', $goodsInfo['warehousing_son_id'])->delete();
        Db::table('db_warehousing_product')->where('warehousing_son_id', $goodsInfo['warehousing_son_id'])->delete();
        //重新写入编辑后的数据
        Db::table('db_tray')->insert($data);
        Db::table('db_warehousing_product')->insertGetId($product);
        $arr = ['tray_number' => count($data), 'box_number' => $goodsInfo['box_number']];
        Db::table('db_warehousing_son')->where('warehousing_son_id', $goodsInfo['warehousing_son_id'])->update($arr);
        return $data['tray_id'];
    }


    public function in($trayId, $goodsInfo, $inData, $packInfo)
    {
        $base = base_convert(uniqid(), 36, 10);
        $idNo = date('ymdHis').substr($base, -6);
        //stock
        $data = [];
        $data['stock_id'] = 'JXRD' . $idNo;
        $data['warehousing_id'] = $goodsInfo['warehousing_id'];
        $data['warehousing_son_id'] = $goodsInfo['warehousing_son_id'];
        $data['tray_id'] = $trayId;
        $data['config_id'] = "20250708142453";
        $data['project_id'] = $inData['project_id'];
        $data['project_client'] = $inData['project_client'];
        $data['number'] = $goodsInfo['number'];
        $data['tray_number'] = 1;
        $data['box_number'] = $goodsInfo['box_number'];
        $data['goods_id'] = $goodsInfo['goods_id'];
        $data['goods_name'] = $goodsInfo['goods_name'];
        $data['goods_Cname'] = $goodsInfo['goods_Cname'];
        $data['goods_Ename'] = $goodsInfo['goods_Ename'];
        $data['supplier_id'] = $goodsInfo['supplier_id'];
        $data['supplier_name'] = $goodsInfo['supplier_name'];
        $data['manufacturer_id'] = $goodsInfo['manufacturer_id'];
        $data['manufacturer_name'] = $goodsInfo['manufacturer_name'];
        $data['packing_id'] = $packInfo['packing_id'];
        $data['p_barcode'] = "";
        $data['packing_num'] = $packInfo['packing_num'];
        $data['unit_name'] = $packInfo['unit_name'];
        $data['created_at'] = time();
        $data['status'] = 0;
        $data['split_status'] = 0;
        $data['tenant_id'] = $goodsInfo['tenant_id'];
        $data['creator_id'] = $goodsInfo['tenant_id'];
        $data['batch_number'] = $goodsInfo['batch_number'];
        $data['Good_Qty'] = $data['number'];
        $parent_id = Db::table('db_warehouse_config')->where('config_id', $data['config_id'])->value('parent_id');
        $grand_parent_id = Db::table('db_warehouse_config')->where('id', $parent_id)->value('parent_id');
        $grand_parent = Db::table('db_warehouse_config')->where('id', $grand_parent_id)->find();
        $data['entrepot_name'] = $grand_parent['name'];
        $data['entrepot_id'] = $grand_parent['config_id'];
        Db::table('db_stock')->insert($data, true);
        return $data['stock_id'];
    }

    public function inLog($stockId, $goodsInfo, $packInfo)
    {
        $data = [];
        $data['stock_id'] = $stockId;
        $data['box_id'] = '';
        $data['slice_id'] = '';
        $data['ext_json'] = json_encode([]);
        $data['order_type'] = 1;
        $data['order_pid'] = $goodsInfo['warehousing_id'];
        $data['order_id'] = $goodsInfo['warehousing_son_id'];
        //操作的这个库存是来自哪一个订单的
        $data['warehousing_id'] = $goodsInfo['warehousing_id'];
        $data['warehousing_son_id'] = $goodsInfo['warehousing_son_id'];
        $data['goods_name'] = $goodsInfo['goods_name'];
        $data['goods_id'] = $goodsInfo['goods_id'];
        $data['packing_id'] = $packInfo['packing_id'];
        $packing_total = $packInfo['packing_num'] * $packInfo['layup_num'];
        $data['packing_specification'] = "1托/{$packInfo['layup_num']}{$packInfo['unit_name']}/{$packing_total}片";
        $data['tenant_id'] = $goodsInfo['tenant_id'];
        $data['creator_id'] = $goodsInfo['creator_id'];
        $data['created_at'] = time();

        return \catchAdmin\storehouse\model\InventoryOperationRecord::insert($data, true);
    }
}